#include"get_id.h"
#include"select_id.h"
 char dest[1024]={0};

size_t header_callback(void *contents, size_t size, size_t nmemb, void *userp)
{
    size_t realsize = size * nmemb;
    char **header_buf = (char **)userp;

    *header_buf = realloc(*header_buf, strlen(*header_buf) + realsize + 1);
    if (*header_buf == NULL)
    {
        fprintf(stderr, "内存分配失败（响应头）\n");
        return 0;
    }

    strncat(*header_buf, (char *)contents, realsize);
    return realsize;
}

// -------------------------- JSON解析获取的数据 --------------------------
void parse_and_print_response_2(const char *response)
{
    if (response == NULL || strlen(response) == 0)
    {
        fprintf(stderr, "解析JSON失败：API返回空响应\n");
        return ;
    }

    struct json_object *root = json_tokener_parse(response);
    if (root == NULL)
    {
        fprintf(stderr, "解析JSON失败：非标准JSON -> %s\n", response);
        return;
    }
    struct json_object *success_obj = NULL, *code_obj = NULL, *msg_obj = NULL;
    json_object_object_get_ex(root, "success", &success_obj);
    json_object_object_get_ex(root, "code", &code_obj);
    json_object_object_get_ex(root, "msg", &msg_obj);


    if (success_obj && json_object_get_boolean(success_obj))
    {
        struct json_object *data_obj = NULL;
        if (json_object_object_get_ex(root, "data", &data_obj))
        {
            const char *mailNo = "未知", *company = "未知", *status = "未知";
            const char *lastTime = "未知", *lastMsg = "未知";
            const char *fromAddress = "未知", *toAddress = "未知", *warehouse = "未知";
            struct json_object *temp = NULL;

            // 基础信息
            if (json_object_object_get_ex(data_obj, "mailNo", &temp))
                mailNo = json_object_get_string(temp);
            if (json_object_object_get_ex(data_obj, "logisticsCompanyName", &temp))
                company = json_object_get_string(temp);
            if (json_object_object_get_ex(data_obj, "logisticsStatusDesc", &temp))
                status = json_object_get_string(temp);
            if (json_object_object_get_ex(data_obj, "theLastTime", &temp))
                lastTime = json_object_get_string(temp);
            if (json_object_object_get_ex(data_obj, "theLastMessage", &temp))
                lastMsg = json_object_get_string(temp);

            // 解析物流轨迹获取地址和仓库信息
            struct json_object *traces_array = NULL;
            if (json_object_object_get_ex(data_obj, "logisticsTraceDetailList", &traces_array) &&
                json_object_is_type(traces_array, json_type_array))
            {
                int array_len = json_object_array_length(traces_array);
                if (array_len > 0)
                {
                    // 获取第一条记录（发件地址）
                    struct json_object *first_trace = json_object_array_get_idx(traces_array, 0);
                    if (json_object_object_get_ex(first_trace, "areaName", &temp))
                    {
                        fromAddress = json_object_get_string(temp);
                    }

                    // 获取最后一条记录（收件地址）
                    struct json_object *last_trace = json_object_array_get_idx(traces_array, array_len - 1);
                    if (json_object_object_get_ex(last_trace, "areaName", &temp))
                    {
                        toAddress = json_object_get_string(temp);
                    }

                    // 从描述中提取详细地址信息
                    if (json_object_object_get_ex(first_trace, "desc", &temp))
                    {
                        const char *desc = json_object_get_string(temp);
                        // 可以从desc中提取更详细的地址信息
                    }
//                     // 智能识别当前仓库（从最新几条记录中查找）
//  int start_index = array_len - 3;  // 查看最后2条记录
//                     if (start_index < 0) {
//                         start_index = 0;  // 如果记录少于2条，从第0条开始
//                     }
                    
//                     for (int i = array_len - 1; i >= start_index; i--) {
//                         struct json_object *trace = json_object_array_get_idx(traces_array, i);
//                         if (json_object_object_get_ex(trace, "desc", &temp)) {
//                             const char *desc = json_object_get_string(temp);
//                             if (strstr(desc, "转运中心") != NULL || 
//                                 strstr(desc, "公司") != NULL ||               
//                                 strstr(desc, "服务中心") != NULL ||
//                                 strstr(desc, "仓库") != NULL ||
//                                 strstr(desc, "分拨") != NULL) {
//                                 warehouse = desc;  // 使用描述作为仓库信息
//                                 break;
//                             }
//                         }
//                     }
                }
            }

            printf("\n=== 物流详情 ===\n");
            printf("单号: %s\n",mailNo);
            printf("发件地区: %s\n收件地区: %s\n当前仓库位置: %s\n",
                   fromAddress, toAddress, warehouse);
                   sprintf(dest," %s %s",fromAddress,toAddress);
       // memcpy(dest,warehouse,sizeof(warehouse));
        }
        else
        {
            printf("\n未找到物流数据（data字段缺失）\n");
        }
    }

    json_object_put(root);
}

// -------------------------- 核心请求函数（关键修复） --------------------------
int send_logistics_request(const char *express_no)
{
    CURL *curl;
    CURLcode res;
    char *response = malloc(1), *header_buf = malloc(1);
    if (response == NULL || header_buf == NULL)
    {
        fprintf(stderr, "内存分配失败（请求初始化）\n");
        free(response);
        free(header_buf);
        return 1;
    }
    response[0] = '\0';
    header_buf[0] = '\0';

    curl = curl_easy_init();
    if (!curl)
    {
        fprintf(stderr, "curl初始化失败\n");
        free(response);
        free(header_buf);
        return 1;
    }

    // -------------------------- 核心修复1：严格拼接JSON请求体 --------------------------
    // 用sprintf替代snprintf，确保格式绝对紧凑（无任何多余字符）
    char post_data[64]; // 足够容纳最长物流单号（通常15-20位）
    // 格式：{"expressNo":"123456789"} → 无空格、无换行，纯ASCII字符
    // 修改请求体拼接方式（键值对格式，而非JSON）
    sprintf(post_data, "expressNo=%s", express_no); // 格式：expressNo=777311736302319
    size_t post_len = strlen(post_data);

    // -------------------------- 核心修复2：强化请求头配置 --------------------------
    struct curl_slist *headers = NULL;
    headers = curl_slist_append(headers, AUTH_HEADER);
    headers = curl_slist_append(headers, CONTENT_TYPE_HEADER);
    // 新增：明确告知API请求体编码为UTF-8（部分API需显式声明）
    headers = curl_slist_append(headers, "Accept-Charset: utf-8");
    headers = curl_slist_append(headers, "User-Agent: curl/7.81.0"); // 模拟标准curl客户端

    // -------------------------- 核心修复3：curl选项强制配置 --------------------------
    curl_easy_setopt(curl, CURLOPT_URL, API_URL);
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    curl_easy_setopt(curl, CURLOPT_POST, 1L);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post_data);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, post_len); // 强制指定长度，避免自动计算偏差
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
    curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, header_callback);
    curl_easy_setopt(curl, CURLOPT_HEADERDATA, &header_buf);
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, TIMEOUT_SEC);
    curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, TIMEOUT_SEC);
    curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); // 开启调试，确认请求体发送情况

    // 执行请求
    printf("\n=== 202发送请求（单号：%s）===", express_no);
    res = curl_easy_perform(curl);

    // 处理结果
    if (res != CURLE_OK)
    {
        fprintf(stderr, "\ncurl失败：%s\n", curl_easy_strerror(res));
    }
    else
    {
        // 打印响应头中的错误信息（精准定位问题）
        if (strstr(header_buf, "X-Ca-Error-Message:"))
        {
            char *err_start = strstr(header_buf, "X-Ca-Error-Message:") + 21;
            char *err_end = strstr(err_start, "\r\n");
            if (err_end)
                *err_end = '\0';
            fprintf(stderr, "\nAPI错误详情：%s\n", err_start);
        }
        printf("\n【请求体】: %s（长度：%zu字节）\n", post_data, post_len); // 验证请求体是否正确
        printf("【原始响应】: %s\n", strlen(response) ? response : "空");
        parse_and_print_response_2(response);
        
    }
    // 清理资源
    curl_slist_free_all(headers);
    curl_easy_cleanup(curl);
    free(response);
    free(header_buf);
return 0;
}
// -------------------------- 查询对应快递单号的信息 --------------------------
char * select_id(const char *target_express_no)
{
   // const char *target_express_no = "777311736302319";
    printf("=========================================\n");
    printf("单号：%s \n", target_express_no);
    curl_global_init(CURL_GLOBAL_DEFAULT);
    send_logistics_request(target_express_no);
    printf("dest收件:%s\n",dest);
    char *dest_company=dest;
    curl_global_cleanup();
    return  dest_company;
}

